import matplotlib.pyplot as plt
import numpy as np

#构造图像
img =  [[  0,  0,  0,255,255,255,255,255],
        [  0,  0,  0,255,  0,  0,  0,255],
        [  0,  0,255,255,  0,  0,  0,255],
        [255,255,255,  0,255,255,255,255],
        [255,  0,  0,  0,255,  0,  0,  0],
        [255,  0,  0,  0,255,  0,  0,  0],
        [255,255,255,255,255,  0,  0,  0]]
img = np.array(img)

# 算法
def img_fill(img, x,y):
    '''
        边界色：255
        填充色：180
    '''
    nbo= lambda pt:[(pt[0]-1,  pt[1]),(pt[0]+1,  pt[1]),
                    (  pt[0],pt[1]-1),(  pt[0],pt[1]+1),
                    (pt[0]-1,pt[1]+1),(pt[0]+1,pt[1]+1),
                    (pt[0]-1,pt[1]-1),(pt[0]+1,pt[1]-1)]
    stack = [] # 栈
    stack.append((x,y)) # 当前像素入栈
    while stack:
        pt = stack.pop()
        if img[pt] != 180: # 判断是否为填充色
            img[pt] = 180
        for p in nbo(pt):
            if img[p] != 180 and img[p] != 255:
                stack.append(p)
    return img

img = img_fill(img, 5,1)

# 保存图像
# plt.imsave("填充.png", img, cmap='gray_r')

# 显示图像
fig=plt.figure()
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray_r')
plt.show()